package mn.idax.exchange.otc.util;

import org.apache.commons.codec.binary.Base64;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @program: auth
 * @description: CryptoUtils
 * @author: zhuwei
 * @create: 2019/04/10 11:37
 */
public class CryptoUtils {

   public static void main(String[] args){


        String passwordSalt = "eszF/D/B/IZjxdTAA0Argy366/eFXybdO9bfAhTWsdpEbvuINobQ28gdG7KdUNGnQoNgFtJajKjg0kfe/vyUpg==";
        String hashedPassword = "1d7c8e8a33760bb9cb8e62217fc0bf10";
        String originPassword = "qwe123";

        String aa   = hashPassword("123456","GHSl23sd");
       LogUtils.info(CryptoUtils.class,"aa="+aa);
        try {
            if(verfifyPassword(hashedPassword,originPassword,passwordSalt)){
                LogUtils.info(CryptoUtils.class,"密码验证通过");
            }else{
                LogUtils.info(CryptoUtils.class,"密码验证不通过");
            }
            createRandomSalt();

       }catch (Exception e){
            e.printStackTrace();
        }
   }

    /**
     * 验证密码
     * @param hashedPassword
     * @param originPassword
     * @param passwordSalt
     * @return
     * @throws Exception
     */
    public static boolean verfifyPassword(String hashedPassword,String originPassword,String passwordSalt){
        if(hashedPassword.equals(hashPassword(originPassword,passwordSalt))){
            return true;
        }
        return false;
    }

    public static String hashPassword(String paswword,String salt) {  //new md5
        MessageDigest messageDigest = null;
        String str = paswword + salt;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            }
            else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return md5StrBuff.toString();
    }

    public static String hashPassword_bak(String paswword,String salt){
        byte[] passwordByte = null;
        byte[] saltByte = null;
        String hashPassword = null;
        try {
            /**16进度**/
            passwordByte =paswword.getBytes("UTF-16LE");
            /**base64**/
            saltByte = DatatypeConverter.parseBase64Binary(salt);

            byte[] passwordAndSalt = new byte[saltByte.length + passwordByte.length];

            System.arraycopy(saltByte,0,passwordAndSalt,0,saltByte.length);
            System.arraycopy(passwordByte,0,passwordAndSalt,saltByte.length,passwordByte.length);
            //SHA 256 算法
            hashPassword= computeHash(passwordAndSalt);
        }catch (Exception e){
            e.printStackTrace();
        }
        return hashPassword;
    }


    /**
     * add zhuwei
     *  SHA 256 算法
     * @param input
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String computeHash(byte[] input) throws NoSuchAlgorithmException {

        // SHA 加密开始
        // 创建加密对象 并傳入加密類型
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        // 得到 byte 類型结果
        byte[] byteBuffer = messageDigest.digest(input);

        return Base64.encodeBase64String(byteBuffer);
    }


    /**
     * 生成加密的盐
     * @return
     */
//    public static String createRandomSalt(){
//        String passwordSalt = null;
//        try{
//            int saltSize = 64;
//            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
//            byte[] salt = random.generateSeed(saltSize);
//            passwordSalt = Base64.encodeBase64String(salt);
//            LogUtils.debug(CryptoUtils.class,"passwordSalt:" + passwordSalt);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        return passwordSalt;
//    }

    public static String createRandomSalt() {
        long start = System.currentTimeMillis();
        String passwordSalt = null;
        try {
            int saltSize = 64;

            Random random = new Random();
            ByteBuffer buffer = ByteBuffer.allocate(saltSize);

            for(int i=0;i<8;i++) {
                buffer.putLong(random.nextLong());
            }

            byte [] salt = buffer.array();
            passwordSalt = Base64.encodeBase64String(salt);
            LogUtils.info(CryptoUtils.class,"auth=generateSaltExpendTime:{}"+(System.currentTimeMillis()-start));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return passwordSalt;
    }


}
